package com.share.user.service.Impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.exception.ServiceException;
import com.share.user.api.domain.UserInfo;
import com.share.user.mapper.UserInfoMapper;
import com.share.user.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class IUserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 调用微信登录接口，获取openid
     * 查询用户是否存在
     * 如果存在就更新用户登录信息
     * 不存在就创建用户
     * @param code
     * @return
     */
    @Override
    public UserInfo wxLogin(String code) {
        WxMaJscode2SessionResult sessionInfo = null;
        String openId = null;
        try {
            //获取openId
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
            log.info("【小程序授权】openId={}", openId);
        } catch (Exception e) {
            log.error("获取openId失败，微信返回结果: {}", JSON.toJSONString(sessionInfo));
            throw new ServiceException("获取用户信息失败");
        }
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if (null == userInfo) {
            userInfo = new UserInfo();
            userInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setWxOpenId(openId);
            this.save(userInfo);
        }
        log.info("【用户信息】{}", JSON.toJSON(userInfo));
        return userInfo;
    }

    /**
     * 模拟调用微信的信誉支付分
     * @return
     */
    @Override
    public Boolean isFreeDeposit() {
        //微信支付分
        //https://pay.weixin.qq.com/wiki/doc/apiv3/payscore.php?chapter=18_1&index=2
        // 默认免押金，模拟实现
        UserInfo userInfo = this.getById(SecurityContextHolder.getUserId());
        userInfo.setDepositStatus("1");
        this.updateById(userInfo);
        return true;
    }


//    /**
//     * 更新用户登录信息,将登录日志存入数据库
//     * //todo: 优化方案日志使用aop+es方案
//     * @param updateUserLogin
//     * @return
//     */
//    @Override
//    public Boolean updateUserLogin(UpdateUserLogin updateUserLogin) {
//        UserInfo userInfo = new UserInfo();
//        userInfo.setId(updateUserLogin.getUserId());
//        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
//        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
//        userInfoMapper.updateById(userInfo);
//
//        //登录日志
//        UserLoginLog userLoginLog = new UserLoginLog();
//        userLoginLog.setUserId(userInfo.getId());
//        userLoginLog.setMsg("小程序登录");
//        userLoginLog.setIpaddr(updateUserLogin.getLastLoginIp());
//        userLoginLogMapper.insert(userLoginLog);
//        return true;
//    }


}
